<template>
  <div class="page">
    <div class="cert-data-content" style="margin-bottom: 16px" v-if="certData">
      <div class="flex-between">
        <div class="cert-title">{{ $t('privateCloud.certtitle') }}</div>
        <rj-space>
          <a-button @click="addLicense()">{{
            $t('privateCloud.certreport')
          }}</a-button>
          <a-button type="primary" @click="exportLicense()">{{
            $t('privateCloud.certrepertt')
          }}</a-button>
        </rj-space>
      </div>
      <div class="itme-row">
        <div class="item-label">{{ $t('privateCloud.mainname') }} ：</div>
        <div>
          {{ certData.subject }}
        </div>
      </div>
      <div class="itme-row">
        <div class="item-label">{{ $t('privateCloud.issuedBy') }} ：</div>
        <div>
          {{ certData.issuedBy }}
        </div>
      </div>
      <div class="itme-row">
        <div class="item-label">{{ $t('privateCloud.issueDay') }} ：</div>
        <div>
          {{ certData.issuedDay }}
        </div>
      </div>
      <div class="itme-row">
        <div class="item-label">{{ $t('privateCloud.expireDay') }} ：</div>
        <div>
          {{ certData.expireDay }}
        </div>
      </div>
      <div class="itme-row">
        <div class="item-label">{{ $t('privateCloud.keyAlgo') }} ：</div>
        <div>
          {{ certData.keyAlgo }}
        </div>
      </div>
      <div class="itme-row">
        <div class="item-label">
          {{ $t('privateCloud.certificateEnabled') }} ：
        </div>
        <div>
          {{
            certData.certificateEnabled == 'Yes'
              ? $t('privateCloud.certstatus')
              : $t('privateCloud.certunuser')
          }}
        </div>
      </div>
      <div class="itme-row">
        <div class="item-label">{{ $t('privateCloud.validStatus') }} ：</div>
        <div>
          {{
            certData.validStatus == 'Valid'
              ? $t('privateCloud.validenable')
              : $t('privateCloud.validubenable')
          }}
        </div>
      </div>
    </div>
    <div class="no-data" v-else>
      <rj-empty :title="$t('privateCloud.certificatetip')"></rj-empty>
      <a-button type="primary" @click="addLicense()">{{
        $t('privateCloud.certificateadd')
      }}</a-button>
    </div>
    <rj-modal
      :title="$t('privateCloud.certificateadd')"
      :visible="visible"
      :maskClosable="false"
      :width="700"
      @ok="handleOk"
      @cancel="handelModalCancel"
    >
      <div class="export-license">
        <div class="warning-info" v-if="certData">
          <icon-font
            type="ic-jinggao_mianxing"
            class="warning"
            style="font-size: 14px"
          />
          {{ $t('privateCloud.replacetip') }}
        </div>
        <div class="error-info" v-if="errorMsg">
          <icon-font type="ic-offline" class="error" style="font-size: 14px" />
          {{ $t('privateCloud.importerror', { reson: errorMsg }) }}
        </div>
        <a-form-model
          :model="form"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          :rules="rules"
          ref="ruleForm"
          :colon="false"
        >
          <a-form-model-item
            prop="fileName"
            :label="$t('privateCloud.certificatedlab1')"
          >
            <a-upload
              :multiple="false"
              :fileList="form.fileList1"
              class="avatar-uploader"
              :before-upload="beforeUpload"
              :accept="accept.toString()"
            >
              <a-button class="a-btn">
                <a-icon type="upload" /> {{ $t('privateCloud.import') }}
              </a-button>
            </a-upload>
          </a-form-model-item>
          <a-form-model-item
            prop="fileNamePrivate"
            :label="$t('privateCloud.certificatedlab2')"
          >
            <a-upload
              :multiple="false"
              :fileList="form.fileList2"
              class="avatar-uploader"
              :before-upload="beforeUploadPrivate"
              :accept="keyaccept.toString()"
            >
              <a-button class="a-btn">
                <a-icon type="upload" /> {{ $t('privateCloud.import') }}
              </a-button>
            </a-upload>
          </a-form-model-item>
          <a-form-model-item
            prop="password"
            :label="$t('privateCloud.certificatedlab3')"
          >
            <a-input-password v-model="form.password"></a-input-password>
          </a-form-model-item>
        </a-form-model>
      </div>

      <div class="box-tip">
        <i18n path="privateCloud.importTip" tag="span">
          <span slot="name" class="import-tip">{{
            $t('privateCloud.importtip1')
          }}</span>
          <span slot="key" class="import-tip">{{
            $t('privateCloud.importtip2')
          }}</span>
        </i18n>
      </div>
    </rj-modal>
    <rj-modal
      :title="$t('privateCloud.certreperttfile')"
      :visible="showExport"
      :maskClosable="false"
      :width="700"
      @ok="handleOkExport"
      @cancel="handelModalCancelExport"
      :okText="$t('privateCloud.exportfilebtn')"
    >
      <div class="export-license">
        <div class="info-info" v-if="certData">
          <icon-font
            type="ic-jinggao_mianxing"
            class="info"
            style="font-size: 14px"
          />
          {{ $t('privateCloud.exporttip') }}
        </div>
        <a-form-model
          :model="outfileForm"
          :label-col="labelCol"
          :wrapper-col="wrapperCol"
          :rules="exportrules"
          ref="exportForm"
          :colon="false"
        >
          <a-form-model-item
            prop="password"
            :label="$t('privateCloud.exportfile')"
          >
            <a-radio-group v-model="outfileForm.protect">
              <a-radio class="radioStyle" :value="1">
                {{ $t('commonChat.yes') }}
              </a-radio>
              <a-radio class="radioStyle" :value="2">
                {{ $t('commonChat.no') }}
              </a-radio>
            </a-radio-group>
          </a-form-model-item>
          <a-form-model-item
            prop="password"
            :label="$t('public.password')"
            v-if="outfileForm.protect == 1"
          >
            <a-input-password v-model="outfileForm.password"></a-input-password>
          </a-form-model-item>
          <a-form-model-item
            prop="repassword"
            :label="$t('public.confirmPwd')"
            v-if="outfileForm.protect == 1"
          >
            <a-input-password
              v-model="outfileForm.repassword"
            ></a-input-password>
          </a-form-model-item>
        </a-form-model>
      </div>
    </rj-modal>
  </div>
</template>
<script>
import { mapState } from 'vuex';
import {
  requestHttp,
  maccApi,
  requestHttpUploadByFormList,
} from '@utils/index';
import { RjModal } from '@components';
import moment from 'moment-timezone';

export default {
  name: 'license',
  props: {},
  components: {
    'rj-modal': RjModal,
  },
  data() {
    let validateName = (rule, value, callback) => {
      let reg = false;
      let deviceNameRegex = /^[\w\-.]+$/;
      if (deviceNameRegex.test(value)) {
        let strByteLen = value.length;
        if (strByteLen >= 0 && strByteLen <= 64) {
          reg = true;
        }
      }
      if (!reg) {
        return callback(
          new Error(this.$t('privateCloud.passvalidate', [1, 64]))
        );
      }
      callback();
    };
    let validateNameRequired = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
        return callback(new Error(this.$t('rip.inputPsw')));
      }
      let reg = false;
      let deviceNameRegex = /^[\w\-.]+$/;
      if (deviceNameRegex.test(value)) {
        let strByteLen = value.length;
        if (strByteLen >= 0 && strByteLen <= 64) {
          reg = true;
        }
      }
      if (!reg) {
        return callback(
          new Error(this.$t('privateCloud.passvalidate', [1, 64]))
        );
      }
      callback();
    };
    let repeatName = (rule, value, callback) => {
      if (value === null || value === undefined || value === '') {
        return callback(new Error(this.$t('rip.inputPsw')));
      }
      let reg = false;
      let deviceNameRegex = /^[\w\-.]+$/;
      if (deviceNameRegex.test(value)) {
        let strByteLen = value.length;
        if (strByteLen >= 0 && strByteLen <= 64) {
          reg = true;
        }
      }
      if (!reg) {
        return callback(
          new Error(this.$t('privateCloud.passvalidate', [1, 64]))
        );
      }
      if (this.outfileForm.password != this.outfileForm.repassword) {
        return callback(new Error(this.$t('bridge.confirmPasswordTips1')));
      }
      callback();
    };

    let validateKey = (rule, value, callback) => {
      value = this.form.fileName;
      if (value === null || value === undefined || value === '') {
        return callback(new Error(this.$t('privateCloud.selimport')));
      }
      callback();
    };
    let validateKey1 = (rule, value, callback) => {
      value = this.form.fileNamePrivate;
      if (value === null || value === undefined || value === '') {
        return callback(new Error(this.$t('privateCloud.selimport')));
      }
      callback();
    };
    return {
      labelCol: { span: 9 },
      wrapperCol: { span: 15 },
      list: [],
      searchParam: {
        auth_type: '',
        online_status: '',
        account: '',
      },
      visible: false,
      form: {
        password: '',
        fileList1: [],
        fileList2: [],
        fileNamePrivate: '',
        fileName: '',
      },
      rules: {
        password: [
          {
            validator: validateName,
            trigger: 'blur',
          },
        ],
        fileName: [
          {
            required: true,
            validator: validateKey,
            trigger: 'blur',
          },
        ],
        fileNamePrivate: [
          {
            required: true,
            validator: validateKey1,
            trigger: 'blur',
          },
        ],
      },
      exportrules: {
        password: [
          {
            required: true,
            validator: validateNameRequired,
            trigger: 'blur',
          },
        ],
        repassword: [
          {
            required: true,
            validator: repeatName,
            trigger: 'blur',
          },
        ],
      },
      accept: ['.crt', '.pem'], //上传类型
      keyaccept: ['.key'], //上传类型

      isExitLicense: false,
      certData: null,
      errorMsg: '',
      licenseStatus: {
        tenantId: 40,
        usedPackage: 0, // 已使用服务包数
        unusedPackage: 204000, // 未使用服务包数,
        totalPackage: 204000, // 服务包总数
        currentMonthUsingPackage: 0,
        currentStatus: 'out-service',
        activeTime: 1561910400000,
        currentMonth: 1559318400000,
        estimateTerminationTime: 2098454400000, // 预估到期时间
      },
      showExport: false,
      outfileForm: { protect: 1, password: '', repassword: '' },
    };
  },

  mounted() {
    this.timezone = this.$store.state.User.userInfo.timeZone;
    this.initView();
  },
  created() {},
  methods: {
    initView() {
      this.getList();
    },
    /**
     *
     * 获取列表
     * */
    async getList() {
      let ret = await requestHttp({
        api: `${maccApi.PRIVATE_HTTPS_CERT_API}`,
        method: 'GET',
        module: 'cube',
      });
      if (ret.data) {
        this.certData = ret.data;
      } else {
        this.certData = null;
      }
    },
    dealTime(value) {
      if (this.timezone) {
        return moment(value).tz(this.timezone).format('YYYY/MM/DD HH:mm:ss');
      }
      return moment(value).format('YYYY/MM/DD HH:mm:ss');
    },
    getTime() {
      if (this.licenseStatus.estimateTerminationTime) {
        let time =
          this.licenseStatus.estimateTerminationTime - new Date().getTime();
        if (time > 0) {
          //在线时长,默认单位s
          let activeTime = parseInt(time / 1000);
          let hour = Math.floor(activeTime / 3600);
          activeTime = activeTime % 3600;
          let minute = Math.floor(activeTime / 60);
          activeTime = activeTime % 60;
          let second = activeTime;
          return hour + 'h ' + minute + 'm ' + second + 's';
        }
      }
      return '--';
    },
    async addLicense() {
      this.visible = true;
    },
    exportLicense() {
      this.showExport = true;
    },
    beforeUpload(file) {
      const fileNames = file.name.split('.') || '';
      const fileType = '.' + fileNames[fileNames.length - 1];
      if (this.accept.indexOf(fileType) > -1) {
        this.form.fileName = file.name;
        this.fileUrl = window.URL.createObjectURL(file);
        this.form.fileList1 = [file];
        this.$refs.ruleForm.validate(async (valid) => {});
        //自定义上传
      } else {
        this.$message.warning(this.$t('components.excelImport.upfailfailure'));
      }
      return false;
    },
    beforeUploadPrivate(file) {
      const fileNames = file.name.split('.') || '';
      const fileType = '.' + fileNames[fileNames.length - 1];
      if (this.keyaccept.indexOf(fileType) > -1) {
        this.form.fileNamePrivate = file.name;
        this.fileUrl = window.URL.createObjectURL(file);
        this.form.fileList2 = [file];
        this.$refs.ruleForm.validate(async (valid) => {});
        //自定义上传
      } else {
        this.$message.warning(this.$t('components.excelImport.upfailfailure'));
      }
      return false;
    },
    handleOk() {
      this.$refs.ruleForm.validate(async (valid) => {
        this.importLicense();
      });
    },
    async importLicense() {
      let api = `${maccApi.PRIVATE_HTTPS_CERT_UPLOAD_API}`;
      this.loading = true;

      this.uploadData = {
        uploadData: JSON.stringify({
          api: api,
          fileName: ['certFile', 'keyFile'],
          module: 'cube',
          method: 'POST',
          contentType: 'multipart/form-data',
        }),
      };
      let params = {
        uploadData: this.uploadData.uploadData,
        files: [this.form.fileList1[0], this.form.fileList2[0]],
      };
      let ops = {
        processData: false,
        mimeType: 'multipart/form-data',
        contentType: false,
      };

      let res = await requestHttpUploadByFormList(
        params,
        { passwd: this.form.password },
        ops
      );
      if (res && res.code == 0) {
        this.fileList = [];
        this.visible = false;
        this.$message.success(this.$t('components.excelImport.importsuccess'));
        this.getList();
      } else {
        if (res.msg) {
          this.errorMsg = res.msg;
        }
        this.$message.error(res.msg);
      }
    },
    handelModalCancel() {
      this.visible = false;
    },
    handleOkExport() {
      this.$refs.exportForm.validate(async (valid) => {
        this.outLicense();
      });
    },
    handelModalCancelExport() {
      this.showExport = false;
    },
  },
  watch: {},
  computed: {},
};
</script>
<style lang="less" scoped>
.page {
  padding: 16px;
}
.flex-between {
  display: flex;
  align-content: center;
  justify-content: space-between;
}
.cert-data-content {
  background: @gray-2;
  padding: 16px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
}
.cert-title {
  color: @gray-10;
  font-size: 14px;
  font-weight: bold;
  display: flex;
  align-items: center;
  &::before {
    content: '';
    width: 4px;
    height: 14px;
    background-color: @theme-color;
    margin-right: 8px;
  }
}
.normal-tip {
  color: @success-color;
}
.error-tip {
  color: @error-color;
}
.fontweight {
  font-weight: bold;
}
.export-license {
  /deep/.ant-form-item {
    margin-bottom: 8px;
    display: flex;
    align-items: center;
  }
}
.step-cls {
  margin-top: 8px;
  font-weight: bold;
}
.box {
  /deep/ .ant-upload-picture-card-wrapper {
    width: 160px;
  }
  /deep/ .ant-upload.ant-upload-select-picture-card {
    width: 104px;
    height: 32px;
  }
  /deep/ .ant-upload {
    padding: 0px;
    background-color: #fff;
    border: 0px;
    margin-left: -16px;
    margin-top: 8px;
  }
}

.no-data {
  margin-top: 150px;
  text-align: center;
}
.box-tip {
  background-color: @gray-3;
  padding: 8px 16px;
  border-radius: 4px;
  color: @gray-9;
}
.avatar-uploader {
  display: flex;
  align-items: center;
}
.a-btn {
  margin-right: 16px;
}
/deep/ .ant-upload-list-item-card-actions {
  display: none;
}

.itme-row {
  display: flex;
  text-align: left;
  color: @gray-10;
  .item-label {
    width: 200px;
    line-height: 32px;
  }
}

.error-info {
  border: 1px solid @red-2;
  background-color: @red-1;
  color: @red-7;
  padding: 4px 8px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  border-radius: 4px;
}
.warning-info {
  border: 1px solid @gold-3;
  background-color: @gold-1;
  padding: 8px 16px;
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  border-radius: 4px;
  color: @gray-9;
}
.warning {
  color: @gold-6;
  font-size: 14px;
  margin-right: 8px;
}
.info-info {
  border: 1px solid @blue-3;
  background-color: @blue-1;
  padding: 8px 16px;
  display: flex;
  align-items: center;
  border-radius: 4px;
  margin-bottom: 20px;
}
.info {
  color: @blue-6;
  font-size: 14px;
  margin-right: 8px;
}
.import-tip {
  color: @gray-7;
}
.error {
  color: @red-6;
  font-size: 14px;
  margin-right: 8px;
}
/deep/ .ant-form-item-label {
  width: 200px;
  text-align: left;
}
</style>
